package cd.tools_test;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;

import cd.network.WifiUtils;

/**
 * 作者：chenda
 * 时间：2019/5/27:10:35
 * 邮箱：
 * 说明：
 */
public class NetworkActivity extends Activity implements View.OnClickListener{

    private TextView tvOutput;
    private EditText etInput;
    private Button btn;


    /**
     * 所需的所有权限信息
     */
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CHANGE_NETWORK_STATE,
            Manifest.permission.CHANGE_WIFI_STATE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_WIFI_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION
    };
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serialport);

        tvOutput = (TextView) findViewById(R.id.tvOutput);
        tvOutput.setMovementMethod(ScrollingMovementMethod.getInstance());
        etInput = (EditText) findViewById(R.id.etInput);
        btn = findViewById(R.id.btn);
        btn.setVisibility(View.VISIBLE);
        btn.setOnClickListener((View.OnClickListener) this);
        btn.setClickable(false);

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);// 监听wifi开关变化的状态
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);// 监听wifi连接状态广播,是否连接了一个有效路由
        this.registerReceiver(wifiBroadcastReceiver, filter);

        if(!requestPermissions()){
            btn.setClickable(true);
        }

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x001) {
            boolean isAllGranted = true;
            for (int i = 0; i < permissions.length; i++) {
                isAllGranted &= (grantResults[i] == PackageManager.PERMISSION_GRANTED);
            }
            if (isAllGranted) {
                btn.setClickable(true);
            } else {
                //TODO
            }
        }
    }

    private boolean requestPermissions() {
        ArrayList<String> toApplyList = new ArrayList<String>();
        for (String perm : NEEDED_PERMISSIONS) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 0x001);
            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        this.unregisterReceiver(wifiBroadcastReceiver);
    }

    /**
     * 监听wifi状态
     */
    BroadcastReceiver wifiBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (state) {
                    case WifiManager.WIFI_STATE_DISABLED: {
                        Log.d("chenda","WIFI已经关闭");
                        tvAppend( "WIFI已经关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_DISABLING: {
                        Log.d("chenda","WIFI正在关闭");
                        tvAppend( "WIFI正在关闭");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLED: {
                        Log.d("chenda","WIFI已经打开");
                        tvAppend( "WIFI已经打开");
                        break;
                    }
                    case WifiManager.WIFI_STATE_ENABLING: {
                        Log.d("chenda","WIFI正在打开");
                        tvAppend( "WIFI正在打开");
                        break;
                    }
                    case WifiManager.WIFI_STATE_UNKNOWN: {
                        Log.d("chenda","WIFI未知状态");
                        tvAppend( "WIFI未知状态");
                        break;
                    }
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (NetworkInfo.State.DISCONNECTED == info.getState()) {
                    // wifi没连接上
                    Log.d("chenda","wifi没连接上");
                    tvAppend( "wifi没连接上");
                    wifiConnecting =false;
                } else if (NetworkInfo.State.CONNECTED == info.getState()) {
                    // wifi连接上了
                    Log.d("chenda","wifi连接上了");
                    tvAppend( "wifi连接上了");
                    wifiConnecting = false;
                } else if (NetworkInfo.State.CONNECTING == info.getState()) {
                    // 正在连接
                    Log.d("chenda","wifi正在连接");
                    tvAppend( "wifi正在连接");
                }

            } else if (WifiManager.SUPPLICANT_STATE_CHANGED_ACTION.equals(intent.getAction())) {
                int linkWifiResult = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, 123);
                if (linkWifiResult == WifiManager.ERROR_AUTHENTICATING) {
                    Log.d("chenda","wifi:密码错误");
                    tvAppend( "wifi:密码错误");
                    wifiConnecting =false;
                }
            } else if (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION.equals(intent.getAction())) {
                Log.d("chenda","wifi扫描完毕");
                tvAppend( "wifi扫描完毕");
            }

        }
    };

    public void tvAppend(final String data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvOutput.append(data);
                tvOutput.append("\n");
                int offset = tvOutput.getLineCount() * tvOutput.getLineHeight();
                if (offset > tvOutput.getHeight()) {
                    tvOutput.scrollTo(0, offset - tvOutput.getHeight());
                }
            }
        });

    }

    @Override
    public void onClick(View view) {
        if(view.getId() == R.id.btn){
            new Thread(new Runnable() {
                @Override
                public void run() {

                    while(true){
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        connectWifi();
                    }
                }
            }).start();
        }
    }

    /*
    *
    *
    * */

    private boolean wifiConnecting = false;
    private void connectWifi(){
        if(wifiConnecting)
            return;
        wifiConnecting=true;

        WifiUtils.setWifiEnabled(this,true);
        Log.d("chenda","NetworkUtil.getNetworkConnectType(this)="+NetworkUtil.getNetworkConnectType(this)+",WifiUtils.getCurrSSID(this).equals(\"AAAAAKS12OcAAwId小米手机\")="+WifiUtils.getCurrSSID(this).equals("AAAAAKS12OcAAwId小米手机"));
        if(NetworkUtil.getNetworkConnectType(this)==2 && WifiUtils.getCurrSSID(this).equals("AAAAAKS12OcAAwId小米手机")){
            wifiConnecting=false;
            return;
        }

        int encryptType = WifiUtils.getWifiEncryptType("WPA");
        WifiUtils.connectWifi(this,"AAAAAKS12OcAAwId小米手机","EF8B201C",encryptType);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
